<template>
  <el-container class="small-footer">
    <el-main class="container">
      <el-form
        ref="ruleFormRef"
        class="add-form"
        :rules="rules"
        :model="form"
        label-position="right"
        label-width="auto"
      >
        <el-row :gutter="20" class="rowbg">
          <el-col :span="24" class="mb10">
            <LabelTitle text="基本信息"></LabelTitle>
          </el-col>
          <el-col :span="8">
            <el-form-item label="企业名称：" prop="enterpriseNameCn">
              <el-input
                v-if="isedit"
                v-model="form.enterpriseNameCn"
                placeholder="请输入企业名称"
                clearable
              />
              <span class="value-text" v-else>{{ form.enterpriseNameCn }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="信用代码：" prop="registrationNumber">
              <el-input
                v-if="isedit"
                v-model="form.registrationNumber"
                placeholder="请输入信用代码"
                clearable
              />
              <span class="value-text" v-else>{{ form.enterpriseNameCn }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规上企业：" prop="aboveScale">
              <el-select
                v-if="isedit"
                v-model="form.aboveScale"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="option in gsqyList"
                  :key="option.key"
                  :label="option.value"
                  :value="option.key"
                />
              </el-select>
              <span class="value-text" v-else>{{
                transk2v(form.aboveScale, gsqyList)
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经营状态：" prop="status">
              <el-select
                v-if="isedit"
                v-model="form.status"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="option in jjzt"
                  :key="option.key"
                  :label="option.value"
                  :value="option.key"
                />
              </el-select>
              <span class="value-text" v-else>{{
                transk2v(form.status, jjzt)
              }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="成立日期：" prop="establishmentDate">
              <el-date-picker
                v-if="isedit"
                v-model="form.establishmentDate"
                type="date"
                style="width: 100%"
                placeholder="选择日期"
              />
              <span class="value-text" v-else>{{
                form.establishmentDate
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注：" prop="remark">
              <el-input
                v-if="isedit"
                type="textarea"
                v-model="form.remark"
                placeholder="请输入备注"
                :rows="1"
                clearable
              />
              <span class="value-text" v-else>{{ form.remark }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="企业人数：" prop="staffCount">
              <el-input
                v-if="isedit"
                v-model="form.staffCount"
                placeholder="请输入企业人数"
                clearable
              />
              <span class="value-text" v-else>{{ form.staffCount }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行业类别：" prop="industryCategory">
              <el-select
                v-if="isedit"
                v-model="form.industryCategory"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="option in iclist"
                  :key="option.icId"
                  :label="option.icName"
                  :value="option.icId"
                />
              </el-select>
              <span class="value-text" v-else>{{
                transIC(form.industryCategory, iclist)
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="rowbg">
          <el-col :span="24" class="mb10">
            <LabelTitle text="负责人信息"></LabelTitle>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人：" prop="legalRepresentative">
              <el-input
                v-if="isedit"
                v-model="form.legalRepresentative"
                placeholder="请输入法人"
                clearable
              />
              <span class="value-text" v-else>{{
                form.legalRepresentative
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="安管负责人：" prop="safetyDirector">
              <el-input
                v-if="isedit"
                v-model="form.safetyDirector"
                placeholder="请输入安管负责人"
                clearable
              />
              <span class="value-text" v-else>{{ form.safetyDirector }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="rowbg">
          <el-col :span="24" class="mb10">
            <LabelTitle text="地址信息"></LabelTitle>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执照地址：" prop="registeredAddress">
              <el-input
                v-if="isedit"
                v-model="form.registeredAddress"
                placeholder="请输入执照地址"
                clearable
              />
              <span class="value-text" v-else>{{
                form.registeredAddress
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际地址：" prop="actualAddress">
              <el-input
                v-if="isedit"
                v-model="form.actualAddress"
                placeholder="请输入实际地址"
                clearable
              />
              <span class="value-text" v-else>{{ form.actualAddress }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="rowbg">
          <el-col :span="24" class="mb10">
            <LabelTitle text="附加信息"></LabelTitle>
          </el-col>
          <el-col :span="24" class="upload-col">
            <div class="upload-col">
              <el-upload
                v-if="isedit"
                class="upload-demo"
                drag
                style="
                  width: 352px;
                  height: 140px;
                  overflow: hidden;
                  border: 1px dashed #d9d9d9;
                "
                :before-upload="beforeUpload"
                :http-request="customUpload"
                multiple
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖到此区域，或点击上传</div>
                <div class="el-upload__tip">仅支持jpg和png</div>
              </el-upload>
              <div
                class="img-box"
                v-for="(item, index) in imglist"
                :key="index"
              >
                <span class="icon-close" v-if="isedit" @click="deleteImg(index)"
                  ><el-icon><Close /></el-icon
                ></span>
                <img class="img-up" :src="item" />
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-main>
    <el-footer class="footer mt20" style="text-align: center">
      <el-button type="primary" class="search-btn" @click="goback"
        >返回</el-button
      >
      <el-button
        type="primary"
        class="reset-btn mr12"
        v-if="!isedit"
        @click="editForm"
        >编辑</el-button
      >
      <el-button type="primary" class="reset-btn" v-else @click="congirm"
        >确定</el-button
      >
    </el-footer>
  </el-container>
</template>

<script setup>
import LabelTitle from '@/components/labeltitle.vue';
import { onMounted, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import {
  addorupdataenterprise,
  qrydetail,
  getDaType,
  industrycategory,
} from '@/api/dazx';
import axios from 'axios';
const emit = defineEmits('close');
const props = defineProps({
  currentData: Object,
});

onMounted(() => {
  getType();
});

let gsqyList = ref([]);
let jjzt = ref([]);
let iclist = ref([]);
const getType = async () => {
  try {
    let res1 = await getDaType({
      paramType: 'above_scale',
    });
    gsqyList.value = res1.data;
    let res2 = await getDaType({
      paramType: 'enterprise_status',
    });
    jjzt.value = res2.data;
    let res3 = await industrycategory({});
    // iclist.value = res3.data
    iclist.value = res3.data.flatMap((el) => el.ics);
  } catch (e) {
    console.error(e);
  }
};

let isedit = ref(false);

const editForm = () => {
  isedit.value = true;
};

let rules = reactive({
  enterpriseNameCn: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
  ],
  registrationNumber: [
    { required: true, message: '请输入信用代码', trigger: 'blur' },
  ],
  aboveScale: [
    { required: true, message: '请选择规上企业', trigger: 'change' },
  ],
  status: [{ required: true, message: '请选择经营状态', trigger: 'change' }],
  establishmentDate: [
    { required: true, message: '请选择成立日期', trigger: 'change' },
  ],
  remark: [{ required: false, message: '请输入备注', trigger: 'blur' }],
  staffCount: [{ required: false, message: '请输入企业人数', trigger: 'blur' }],
  industryCategory: [
    { required: true, message: '请选择行业类别', trigger: 'change' },
  ],
  legalRepresentative: [
    { required: true, message: '请输入法人', trigger: 'blur' },
  ],
  safetyDirector: [
    { required: true, message: '请输入安管负责人', trigger: 'blur' },
  ],
  registeredAddress: [
    { required: true, message: '请输入执照地址', trigger: 'blur' },
  ],
  actualAddress: [
    { required: true, message: '请输入实际地址', trigger: 'blur' },
  ],
});
let form = ref({
  enterpriseNameCn: '',
  registrationNumber: '',
  aboveScale: '',
  status: '',
  establishmentDate: null,
  remark: '',
  staffCount: '',
  industryCategory: '',
  legalRepresentative: '',
  safetyDirector: '',
  registeredAddress: '',
  actualAddress: '',
});
let imglist = ref([]);
const getDetail = async (id) => {
  try {
    let { data } = await qrydetail({
      enterpriseId: id,
    });
    form.value = data;
    imglist.value = data.picFiles;
  } catch (e) {
    console.error(e);
  }
};

watch(
  () => props.currentData,
  (newData) => {
    if (newData.id) {
      getDetail(newData.id);
    } else {
      isedit.value = true;
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt1M = file.size / 1024 / 1024 < 1;
  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt1M) {
    ElMessage.error('上传图片大小不能超过 1MB!');
  }
  return isJPG && isLt1M;
};

// 上传
const customUpload = async (options) => {
  const { file, onSuccess, onError, onProgress } = options;
  const formData = new FormData();
  formData.append('picfile', file);
  try {
    let { data } = await axios.post(
      '/integrated-workbench/v1/data-center/global/filedeal/picupload',
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }
    );
    imglist.value.push(data.data.picUrl);
    // console.log('111111111',imglist.value)
  } catch (error) {
    console.error(error);
  }
};

// 删除图片
const deleteImg = (index) => {
  imglist.value.splice(index, 1);
};

// 返回

const goback = () => {
  emit('close');
};

// 确认
let ruleFormRef = ref();
const congirm = () => {
  try {
    ruleFormRef.value.validate(async (valid, fields) => {
      if (!valid) return;
      let { data } = await addorupdataenterprise({
        ...form.value,
        picFiles: imglist.value,
      });
      ElMessage({
        message: form.value.id ? '编辑成功' : '新增成功',
        type: 'success',
      });
      isedit.value = false;
      // goback();
    });
  } catch (e) {
    console.error(e);
  }
};

const transk2v = (value, list) => {
  let text = list.filter((item) => item.key == value);
  return text.length > 0 ? text[0].value : value;
};

const transIC = (icId, list) => {
  let text = list.filter((item) => item.icId == icId);
  return text.length > 0 ? text[0].icName : icId;
};
</script>

<style lang="scss">
.small-footer {
  .el-footer {
    height: 36px !important;
    margin-top: 12px;
  }
}
.rowbg {
  background: #ffffff;
  box-shadow: 0px 0px 29px 0px rgba(70, 102, 149, 0.06);
  border-radius: 12px;
  padding: 16px 40px 0px 40px;
  margin-bottom: 20px;
  .el-form-item {
    margin-bottom: 16px;
  }
}
.container {
  &::-webkit-scrollbar {
    width: 2px;
    height: 4px;
    // height: .04rem;
  }

  /*定义滚动条轨道 内阴影+圆角*/
  &::-webkit-scrollbar-track {
    border-radius: 0.03rem;
    /* background-color: rgb(255 255 255); */
    width: 2px;
  }

  /*定义滑块 内阴影+圆角*/
  &::-webkit-scrollbar-thumb {
    border-radius: 2px;
    background-color: #eee;
    border-radius: 2px;
    background: #ccc;
  }

  /*交叉方块*/
  &::-webkit-scrollbar-corner {
    background-color: rgb(255 255 255);
  }
}
.el-upload-dragger {
  padding: 0 !important;
  border: 0 !important;
  &:hover {
    border: 0 !important;
  }
}

.upload-col {
  display: flex;
  align-items: top;
  padding-bottom: 8px;
}
.img-up {
  width: 272px;
  height: 140px;
  margin: 0 20px;
}
.img-box {
  position: relative;
  .icon-close {
    display: none;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    font-size: 30px;
    position: absolute;
    right: 0px;
    top: -12px;
    cursor: pointer;
    z-index: 999;
    background: #fff;
    border-radius: 50%;
  }
  // .img-up:hover {
  //   .icon-close {
  //     display: block;
  //     z-index: 999;
  //   }
  // }
  &:hover {
    .icon-close {
      display: block;
      z-index: 999;
    }
  }
}
.value-text {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
  line-height: 22px;
  text-align: left;
}
</style>
